package com.huike.pmps.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huike.pmps.dao.BusinessOpportunityDao;
import com.huike.pmps.model.constants.GlobalConstants;
import com.huike.pmps.model.dto.common.PageInfo;
import com.huike.pmps.model.entity.BusinessOpportunity;
import com.huike.pmps.model.entity.Provinces;
import com.huike.pmps.model.entity.Region;
import com.huike.pmps.model.vo.PageResult;
import com.huike.pmps.model.vo.Result;
import com.huike.pmps.service.BusinessOpportunityService;
import com.huike.pmps.service.ProvincesService;
import com.huike.pmps.service.RegionService;
import com.huike.pmps.utils.PmpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 作者：谌贵斌(黑桃K)
 * 日期: 2888-08-08
 * 老师QQ: 272488352
 * 官方QQ交流群: 377748272
 * 刀客程序员官网：http://www.daoke360.com
 * 刀客程序员淘宝旗舰店：https://daoke360.taobao.com/
 */
@Service
@Slf4j
public class BusinessOpportunityServiceImpl implements BusinessOpportunityService {
    @Autowired
    RegionService regionService;
    @Autowired
    ProvincesService provincesService;
    @Autowired
    BusinessOpportunityDao businessOpportunityDao;

    @Override
    public Result insertByImportBusinessOpportunity(MultipartFile file) {

        if (file.isEmpty()) {
            return Result.failure("文件为空");
        }
        try {
            //根据路径获取这个操作excel的实例
            XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
            //根据页面index 获取sheet页
            XSSFSheet sheet = wb.getSheetAt(0);
            //获取标题行
            XSSFRow titleRow = sheet.getRow(0);
            String[] titleRowArray = new String[]{"战区", "省区", "负责人", "对应客户", "商机标题", "产品编号", "销售阶段", "预计签单日期", "预计合同金额（元）", "产品品类", "产品名称", "商机编号", "产品数量"};
            for (int i = 0; i < titleRowArray.length; i++) {
                if (!titleRowArray[i].equals(titleRow.getCell(i).getStringCellValue()))
                    return Result.failure("供应商模板标题行已被修改，请勿修改供应商模板标题行");
            }

            List<BusinessOpportunity> businessOpportunityList = new ArrayList<>();

            XSSFRow row = null;
            Date date = new Date();
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                //获取每一行数据
                row = sheet.getRow(i);

                Integer regionId, provinceId = null;
                String regionName, provinceName = null;
                if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).toString())) {
                    return Result.success("第" + i + "条数据,战区为空，本次导入全部失败");
                } else {
                    Region region = regionService.selectOneByRegionName(row.getCell(0).toString().substring(0, 2));
                    if (region != null) {
                        regionId = region.getId();
                        regionName = region.getRegion();
                    } else {
                        return Result.success("第" + i + "条数据,战区数据填写有误,请按规则填写");
                    }
                }
                if (row.getCell(1) == null || StringUtils.isBlank(row.getCell(1).toString())) {
                    return Result.success("第" + i + "条数据,省份为空，本次导入全部失败");
                } else {
                    Provinces provinces = provincesService.selectByProvinceName(row.getCell(1).toString().substring(0, 2));
                    if (provinces != null) {
                        provinceId = provinces.getProvinceId();
                        provinceName = provinces.getProvince();
                    } else {
                        return Result.success("第" + i + "条数据,省份数据填写有误,请按规则填写");
                    }
                }
                //负责人
                String chargeName = row.getCell(2) == null || StringUtils.isBlank(row.getCell(2).toString()) ? null : row.getCell(2).toString();
                //客户名称
                String customerName = row.getCell(3) == null || StringUtils.isBlank(row.getCell(3).toString()) ? null : row.getCell(3).toString();
                //商机标题
                String boTitle = row.getCell(4) == null || StringUtils.isBlank(row.getCell(4).toString()) ? null : row.getCell(4).toString();
                //产品编号
                String productNo = row.getCell(5) == null || StringUtils.isBlank(row.getCell(5).toString()) ? null : row.getCell(5).toString();
                //销售阶段
                XSSFCell stageCell = row.getCell(6);
                Double stage = null;
                if (stageCell != null && StringUtils.isNotBlank(stageCell.toString())) {
                    if (stageCell.toString().contains("赢单") || stageCell.toString().contains("输单")) continue;
                    if (stageCell.toString().contains(".")) {
                        stage = Double.valueOf(stageCell.toString());
                    }
                    if (stageCell.toString().contains("%")) {
                        stage = Double.valueOf(stageCell.toString().substring(0, stageCell.toString().length() - 1)) / 100;
                    }
                }
                //预计签约日期
                if (row.getCell(7) == null || StringUtils.isBlank(row.getCell(7).toString()))
                    return Result.success("第" + i + "条数据,预计签约日期为空，本次导入全部失败");
                Date signDate = row.getCell(7).getDateCellValue();
                Integer year = PmpUtil.getDateInfo(signDate, GlobalConstants.YEAR);
                Integer seasonOfYear = PmpUtil.getDateInfo(signDate, GlobalConstants.SEASON);
                Integer monthOfYear = PmpUtil.getDateInfo(signDate, GlobalConstants.MONTH);
                Integer weekOfYear = PmpUtil.getDateInfo(signDate, GlobalConstants.WEEK_OF_YEAR);
                Integer weekOfMonth = PmpUtil.getDateInfo(signDate, GlobalConstants.WEEK_OF_MONTH);

                //预计合同金额
                BigDecimal contractAmount = row.getCell(8) == null || StringUtils.isBlank(row.getCell(8).toString()) ? null : BigDecimal.valueOf(Double.valueOf(row.getCell(8).toString()));

                if (row.getCell(9) == null || StringUtils.isBlank(row.getCell(9).toString()))
                    return Result.success("第" + i + "条数据,产品品类为空，本次导入全部失败");
                String productCategory = row.getCell(9).toString();
                Integer productTypeId = null;
                String productTypeName = null;
                if (productCategory.contains("在线资源建设和运营服务")) {
                    productTypeId = 1;
                    productTypeName = "基于高校邦的课程运营服务";
                }
                if (productCategory.contains("在线学习平台产品")) {
                    productTypeId = 2;
                    productTypeName = "精品在线开放课程产品";
                }
                if (productCategory.contains("在线资源内容产品")) {
                    productTypeId = 3;
                    productTypeName = "课程拍摄与制作服务";
                }
                if (productCategory.contains("在线资源内容产品")) {
                    productTypeId = 4;
                    productTypeName = "高校邦学习平台";
                }

                //产品名称
                String productName = row.getCell(10) == null || StringUtils.isBlank(row.getCell(10).toString()) ? null : row.getCell(10).toString();
                //商机编号
                String boNo = row.getCell(11) == null || StringUtils.isBlank(row.getCell(11).toString()) ? null : row.getCell(11).toString();
                //产品数量
                Integer productNumber = row.getCell(12) == null || StringUtils.isBlank(row.getCell(12).toString()) ? null : Double.valueOf(row.getCell(12).toString()).intValue();

                BusinessOpportunity businessOpportunity = BusinessOpportunity.builder().boNo(boNo).boTitle(boTitle).regionId(regionId).regionName(regionName)
                        .provinceId(provinceId).provinceName(provinceName).chargeName(chargeName).customerName(customerName)
                        .productNumber(productNumber).stage(stage).contractAmount(contractAmount).signDate(signDate).year(year)
                        .productCategory(productCategory).productTypeId(productTypeId).productTypeName(productTypeName)
                        .weekOfYear(weekOfYear).weekOfMonth(weekOfMonth).seasonOfYear(seasonOfYear).monthOfYear(monthOfYear).createTime(date)
                        .build();

                //businessOpportunityList.add(businessOpportunity);
                QueryWrapper<BusinessOpportunity> queryWrapper = new QueryWrapper<>();
                queryWrapper.like("bo_no", boNo);
                queryWrapper.like("product_no", productNo);
                BusinessOpportunity one = businessOpportunityDao.selectOne(queryWrapper);
                if (one != null)
                    businessOpportunity.setId(one.getId());
                businessOpportunityList.add(businessOpportunity);
            }

            if (businessOpportunityList.size() > 0) {
                for (BusinessOpportunity businessOpportunity : businessOpportunityList) {
                    if (businessOpportunity.getId() != null) {
                        businessOpportunityDao.updateById(businessOpportunity);
                    } else {
                        businessOpportunityDao.insert(businessOpportunity);
                    }
                }
                return Result.success();
            } else {
                return Result.failure("表格中没有数据");
            }
        } catch (IOException e) {
            log.error(e.getMessage());
            return Result.failure("导入失败，读取表格数据异常" + e.getMessage());
        }
    }

    @Override
    public Result selectByCondition(PageInfo pageInfo, Integer regionId, Integer provinceId, String boNo, String boTitle, String chargeName, String customerName, String productName) {
        QueryWrapper<BusinessOpportunity> queryWrapper = new QueryWrapper<>();
        if (regionId != null)
            queryWrapper.eq("region_id", regionId);
        if (provinceId != null)
            queryWrapper.eq("province_id", provinceId);
        if (StringUtils.isNotBlank(boNo))
            queryWrapper.eq("bo_no", boNo);
        if (StringUtils.isNotBlank(boTitle))
            queryWrapper.eq("bo_title", boTitle);
        if (StringUtils.isNotBlank(chargeName))
            queryWrapper.eq("charge_name", chargeName);
        if (StringUtils.isNotBlank(customerName))
            queryWrapper.eq("customer_name", customerName);
        if (StringUtils.isNotBlank(productName))
            queryWrapper.eq("product_name", productName);

        Page<BusinessOpportunity> page = new Page<>(pageInfo.getPage(), pageInfo.getPageSize());
        Page<BusinessOpportunity> pageList = businessOpportunityDao.selectPage(page, queryWrapper);
        if (pageList.getSize() > 0) {
            PageResult pageResult = PageResult.builder().pageNumber(pageList.getCurrent()).pageSize(pageList.getSize())
                    .total(pageList.getTotal()).rows(pageList.getRecords()).build();
            return Result.success(pageResult);
        } else {
            return Result.success("没有符合条件的记录");
        }

    }


}
